package com.rms.recruit_management_system.controller;

import cn.hutool.crypto.digest.MD5;
import com.rms.recruit_management_system.pojo.Administrator;
import com.rms.recruit_management_system.service.impl.AdministratorServiceImpl;
import com.rms.recruit_management_system.utils.JwtUtil;
import com.rms.recruit_management_system.utils.Result;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@RestController
@Tag(name = "管理员控制类", description = "用于对管理员进行业务操作")
public class AdministratorController {

    @Autowired
    private AdministratorServiceImpl administratorService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 管理员登录
     * @param administrator
     * @return
     */
    @Operation(summary = "管理员登录",description = "根据管理员用户名和密码进行登录")
    @RequestMapping("/admin/login")
    public Result adminLogin(@RequestBody Administrator administrator) {
        Administrator administrators = administratorService.adminLogin(administrator);
        System.out.println(administrators);
        if (administrators != null && administrators.getIsEnabled() == 1)  {
            Map<String,Object> administratorMap = new HashMap<>();
            administratorMap.put("adminId",administrators.getAdminId());
            administratorMap.put("username",administrators.getUsername());
            administratorMap.put("role",administrators.getRole());
            String jwt=JwtUtil.generateToken(administrators.getUsername(),administrators.getAdminId());
            Map<String,Object> map=new HashMap<>();
            map.put("administrator",administratorMap);
            map.put("token",jwt);
            administrators.setLastLoginTime(LocalDateTime.now());
            administratorService.updateAdministrator(administrators);
            return new Result<>(200, "登录成功", map);
        } else {
            return new Result<>(400, "登录失败");
        }
    }

    /**
     * 获取所有普通管理员
     * @return
     */
    @Operation(summary = "获取所有管理员信息",description = "获取所有管理员信息")
    @RequestMapping("/admin/getAdministratorList")
    public Result<List<Administrator>> getAllAdmin() {
        String key="admin_";
        List<Administrator> administrators=(List)redisTemplate.opsForValue().get(key);
        if(administrators!=null && administrators.size()>0){
            return new Result<>(200, "查询成功", administrators);
        }
        administrators = administratorService.getAdministratorList();
        redisTemplate.opsForValue().set(key,administrators,60, TimeUnit.SECONDS);
        return new Result<>(200, "查询成功", administrators);
    }

    /**
     * 修改管理员
     * @param administrator
     * @return
     */
    @Operation(summary = "修改管理员信息",description = "根据id修改管理员信息")
    @RequestMapping("/admin/updateAdministrator")
    public Result<?> updateAdministrator(@RequestBody Administrator administrator) {
        administrator.setPassword(MD5.create().digestHex(administrator.getPassword()));
        administratorService.updateAdministrator(administrator);

        cleanCache("admin_*");
        return new Result<>(200, "修改成功",administrator);
    }

    /**
     * 添加管理员
     * @param administrator
     * @return
     */
    @Operation(summary = "添加管理员信息",description = "添加管理员信息")
    @RequestMapping("/admin/addAdministrator")
    public Result<?> addAdministrator(@RequestBody Administrator administrator) {
        administratorService.addAdministrator(administrator);
        cleanCache("admin_*");
        return new Result<>(200, "添加成功",administrator);
    }

    /**
     * 删除管理员
     * @param adminId
     * @return
     */
    @Operation(summary = "删除管理员信息",description = "根据id删除管理员信息")
    @RequestMapping("/admin/deleteAdministrator/{adminId}")
    public Result<?> deleteAdministrator(@PathVariable Integer adminId) {
        administratorService.deleteAdministrator(adminId);
        cleanCache("admin_*");
        return new Result<>(200, "删除成功");
    }
    @Operation(summary = "批量删除管理员信息",description = "根据id批量删除管理员信息")
    @RequestMapping("/admin/batchDeleteAdministrator")
    public Result<?> batchDeleteAdministrator(@RequestBody List<Integer> adminIdList) {
        administratorService.batchDeleteAdministrator(adminIdList);
        return new Result<>(200, "删除成功");
    }

    @Operation(summary = "查询管理员信息",description = "根据管理员id查询管理员信息")
    @RequestMapping("/admin/getAdminByAdminId/{adminId}")
    public Result<?> getAdminByAdminId(@PathVariable Integer adminId, @RequestHeader("Authorization") String token)  {
        boolean validate = JwtUtil.validateToken(token);
        System.out.println(validate);
        if(!validate){
            return new Result<>(401, "参数错误");
        }
        if(adminId==null){
            return new Result<>(401, "参数错误");
        }
        String key="admin_"+adminId;
        Administrator administrator= (Administrator) redisTemplate.opsForValue().get(key);
        if (administrator!=null) {
            return new Result<>(200, "查询成功", administrator);
        }
        administrator = administratorService.findAdminByAdminId(adminId);
        redisTemplate.opsForValue().set(key,administrator,60,TimeUnit.SECONDS);
        return new Result<>(200, "查询成功", administrator);
    }

    /**
     * 清空缓存
     * @param pattern
     */
    public void cleanCache(String pattern){
        Set keys=redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
